# -*- coding: utf-8 -*-
"""
问答服务层

功能说明:
- 提供统一的问答服务接口
- 集成秘塔AI问答API
- 处理模型别名映射与最小参数校验
- 为控制器提供稳定的业务调用入口

作者: MetasoCreator Team
创建时间: 2025-08-21
"""

from typing import Dict, Any, List, Optional
from datetime import datetime

from .metaso_client import get_metaso_client, MetasoAPIError


class QAService:
	"""
	问答服务类
	
	职责:
	- 参数预处理与别名映射
	- 调用外部秘塔问答API
	- 统一错误响应结构
	"""

	def __init__(self) -> None:
		self.client = get_metaso_client()

	def ask_question(self, messages: List[Dict[str, str]], scope: Optional[str] = None, model: Optional[str] = None) -> Dict[str, Any]:
		"""
		执行问答
		
		Args:
			messages: 对话消息列表，形如[{"role":"user","content":"..."}]
			scope: 搜索范围，可选
			model: 模型标识，支持别名
		
		Returns:
			Dict: 上游返回的扁平结构（包含choices/usage等）或标准错误结构
		"""
		try:
			# 最小校验
			if not messages or not isinstance(messages, list):
				return self._create_error_response("messages参数必须是非空列表")
			for i, message in enumerate(messages):
				if not isinstance(message, dict) or 'role' not in message or 'content' not in message:
					return self._create_error_response(f"messages[{i}]格式错误")

			# 模型别名映射
			mapped_model = self._map_model_alias(model)

			# 调用外部客户端
			result = self.client.ask_question(messages=messages, scope=scope, model=mapped_model)
			return result

		except MetasoAPIError as e:
			return self._create_error_response(str(e))
		except Exception:
			return self._create_error_response("问答服务发生未知错误")

	def _map_model_alias(self, model: Optional[str]) -> str:
		"""将前端模型名映射为客户端支持的模型名。"""
		if not model:
			return 'fast_thinking'
		alias_map = {
			'fast_thinking': 'fast_thinking',
			'deep_thinking': 'da_vinci',
			'da_vinci': 'da_vinci',
			'gpt-4': 'da_vinci',
			'gpt4': 'da_vinci'
		}
		return alias_map.get(model, 'fast_thinking')

	def _create_error_response(self, message: str) -> Dict[str, Any]:
		"""创建统一错误响应。"""
		return {
			'success': False,
			'error': message,
			'timestamp': datetime.now().isoformat(),
			'choices': [],
			'usage': {}
		} 